/**
 * 统一表单验证工具
 * 整合所有表单验证相关的逻辑和规则
 */

import type { FormRules } from 'element-plus'
import { useUnifiedSettings } from '@/composables/useUnifiedSettings'

// 验证规则类型定义
export interface ValidationRule {
  required?: boolean
  message?: string
  trigger?: 'blur' | 'change'
  min?: number
  max?: number
  len?: number
  pattern?: RegExp
  validator?: (rule: any, value: any, callback: any) => void
}

// 常用验证规则
export const commonRules = {
  // 用户名验证
  username: (min = 2, max = 20): ValidationRule[] => [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min, max, message: `用户名长度在 ${min} 到 ${max} 个字符`, trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9_]{2,20}$/, 
      message: '用户名只能包含字母、数字和下划线', 
      trigger: 'blur' 
    }
  ],

  // 密码验证
  password: (minLength = 6, maxLength = 20): ValidationRule[] => [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { 
      min: minLength, 
      max: maxLength, 
      message: `密码长度在 ${minLength} 到 ${maxLength} 个字符`, 
      trigger: 'blur' 
    },
    {
      pattern: new RegExp(`^(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z\\d@$!%*?&]{${minLength},${maxLength}}$`),
      message: '密码必须包含字母和数字',
      trigger: 'blur'
    }
  ],

  // 确认密码验证
  confirmPassword: (passwordField = 'password'): ValidationRule[] => [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        const form = rule.fullField?.split('.')[0] ? rule.fullField.split('.')[0] : 'form'
        const password = document.querySelector(`[name="${passwordField}"]`) as HTMLInputElement
        if (value !== password?.value) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],

  // 邮箱验证
  email: (): ValidationRule[] => [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: '请输入正确的邮箱格式',
      trigger: 'blur'
    }
  ],

  // 手机号验证
  phone: (): ValidationRule[] => [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号格式',
      trigger: 'blur'
    }
  ],

  // 验证码验证
  captcha: (length = 4): ValidationRule[] => [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: length, message: `验证码长度为 ${length} 位`, trigger: 'blur' },
    { 
      pattern: new RegExp(`^[a-zA-Z0-9]{${length}}$`), 
      message: '验证码只能包含字母和数字', 
      trigger: 'blur' 
    }
  ],

  // 数字验证
  number: (min?: number, max?: number): ValidationRule[] => {
    const rules: ValidationRule[] = [
      { required: true, message: '请输入数字', trigger: 'blur' },
      {
        pattern: /^\d+$/,
        message: '请输入有效的数字',
        trigger: 'blur'
      }
    ]
    
    if (min !== undefined) {
      rules.push({
        validator: (rule: any, value: any, callback: any) => {
          if (Number(value) < min) {
            callback(new Error(`数值不能小于 ${min}`))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      })
    }
    
    if (max !== undefined) {
      rules.push({
        validator: (rule: any, value: any, callback: any) => {
          if (Number(value) > max) {
            callback(new Error(`数值不能大于 ${max}`))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      })
    }
    
    return rules
  },

  // 必填验证
  required: (message = '此字段为必填项'): ValidationRule[] => [
    { required: true, message, trigger: 'blur' }
  ],

  // 长度验证
  length: (min: number, max: number, message?: string): ValidationRule[] => [
    { 
      min, 
      max, 
      message: message || `长度在 ${min} 到 ${max} 个字符`, 
      trigger: 'blur' 
    }
  ],

  // 正则验证
  pattern: (pattern: RegExp, message: string): ValidationRule[] => [
    { pattern, message, trigger: 'blur' }
  ]
}

// 动态验证规则生成器
export class ValidationRuleGenerator {
  private settings: ReturnType<typeof useUnifiedSettings>

  constructor() {
    this.settings = useUnifiedSettings()
  }

  // 生成登录表单验证规则
  generateLoginRules(): FormRules {
    const { settings } = this.settings
    const rules: FormRules = {
      username: commonRules.username(),
      password: commonRules.password(
        settings.value.security.passwordMinLength,
        settings.value.security.passwordMaxLength
      )
    }

    // 如果启用验证码，添加验证码验证规则
    if (settings.value.captcha.enabled) {
      rules.captcha = commonRules.captcha(settings.value.captcha.length)
    }

    return rules
  }

  // 生成用户表单验证规则
  generateUserRules(): FormRules {
    return {
      username: commonRules.username(),
      email: commonRules.email(),
      phone: commonRules.phone(),
      password: commonRules.password(),
      confirmPassword: commonRules.confirmPassword('password')
    }
  }

  // 生成设置表单验证规则
  generateSettingsRules(category: string): FormRules {
    const { settings } = this.settings
    const rules: FormRules = {}

    switch (category) {
      case 'security':
        rules.passwordMinLength = commonRules.number(4, 20)
        rules.passwordMaxLength = commonRules.number(6, 30)
        rules.sessionTimeout = commonRules.number(5, 1440)
        rules.maxLoginAttempts = commonRules.number(1, 10)
        break
      
      case 'captcha':
        rules.length = commonRules.number(2, 6)
        break
      
      case 'performance':
        rules.cacheExpiry = commonRules.number(60, 86400)
        rules.maxConcurrentRequests = commonRules.number(1, 50)
        rules.requestTimeout = commonRules.number(1000, 60000)
        break
      
      case 'notification':
        rules.soundVolume = commonRules.number(0, 100)
        break
    }

    return rules
  }

  // 生成自定义验证规则
  generateCustomRules(fieldRules: Record<string, ValidationRule[]>): FormRules {
    const rules: FormRules = {}
    
    Object.keys(fieldRules).forEach(field => {
      rules[field] = fieldRules[field]
    })
    
    return rules
  }
}

// 验证工具函数
export const validationUtils = {
  // 验证邮箱格式
  isValidEmail: (email: string): boolean => {
    return /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)
  },

  // 验证手机号格式
  isValidPhone: (phone: string): boolean => {
    return /^1[3-9]\d{9}$/.test(phone)
  },

  // 验证密码强度
  getPasswordStrength: (password: string): { score: number; level: string; message: string } => {
    let score = 0
    let message = ''

    if (password.length >= 8) score += 1
    if (password.length >= 12) score += 1
    if (/[a-z]/.test(password)) score += 1
    if (/[A-Z]/.test(password)) score += 1
    if (/\d/.test(password)) score += 1
    if (/[^a-zA-Z0-9]/.test(password)) score += 1

    if (score <= 2) {
      return { score, level: 'weak', message: '密码强度较弱' }
    } else if (score <= 4) {
      return { score, level: 'medium', message: '密码强度中等' }
    } else {
      return { score, level: 'strong', message: '密码强度较强' }
    }
  },

  // 验证身份证号
  isValidIdCard: (idCard: string): boolean => {
    const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    return reg.test(idCard)
  },

  // 验证URL格式
  isValidUrl: (url: string): boolean => {
    try {
      new URL(url)
      return true
    } catch {
      return false
    }
  },

  // 验证IP地址
  isValidIP: (ip: string): boolean => {
    const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
    const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/
    return ipv4Regex.test(ip) || ipv6Regex.test(ip)
  }
}

// 表单验证状态管理
export class FormValidationManager {
  private formRef: any = null
  private validationState: Map<string, boolean> = new Map()

  // 设置表单引用
  setFormRef(ref: any) {
    this.formRef = ref
  }

  // 验证整个表单
  async validateForm(): Promise<boolean> {
    if (!this.formRef) return false
    
    try {
      await this.formRef.validate()
      return true
    } catch (error) {
      return false
    }
  }

  // 验证指定字段
  async validateField(field: string): Promise<boolean> {
    if (!this.formRef) return false
    
    try {
      await this.formRef.validateField(field)
      this.validationState.set(field, true)
      return true
    } catch (error) {
      this.validationState.set(field, false)
      return false
    }
  }

  // 清除验证
  clearValidation(fields?: string[]) {
    if (!this.formRef) return
    
    if (fields) {
      fields.forEach(field => {
        this.formRef.clearValidate(field)
        this.validationState.set(field, false)
      })
    } else {
      this.formRef.clearValidate()
      this.validationState.clear()
    }
  }

  // 重置表单
  resetForm() {
    if (!this.formRef) return
    
    this.formRef.resetFields()
    this.validationState.clear()
  }

  // 获取验证状态
  getValidationState(field?: string): boolean | Map<string, boolean> {
    if (field) {
      return this.validationState.get(field) || false
    }
    return this.validationState
  }
}

// 导出默认实例
export const validationRuleGenerator = new ValidationRuleGenerator()
export const formValidationManager = new FormValidationManager()
